<template>
	<el-upload
		class="avatar-uploader"
		action="/api/hzadmin/public/upload_image/"
		:show-file-list="false"
		:on-success="handleAvatarSuccess"
		:before-upload="beforeAvatarUpload"
	>
		<img
			v-if="imgUrl"
			:src="'/api/' + imgUrl"
			class="avatar"
		/>
		<el-icon v-else class="avatar-uploader-icon">
			<Plus />
		</el-icon>

		<el-icon v-if="imgUrl" class="avatar-delete" @click.stop="cleanAvatar" color="#F56C6C">
			<CircleCloseFilled/>
		</el-icon>
	</el-upload>
</template>

<!--
头像上传组件
v-model: 你的头像字段，值是图片上传成功后返回的地址。

@fileChange(file: File)： 如果你想拿到文件File对象，请监听这个事件，


@example
<AvatarUploader v-model="your_avatar"/>
-->

<script setup lang="ts">

import {CircleCloseFilled, DeleteFilled, Plus} from "@element-plus/icons-vue";
import {ref, defineProps, defineEmits, onMounted} from 'vue'
import {useMessage} from "/@hooks/message";


const imgUrl = ref('')
const props = defineProps({
	modelValue: String,
})

const emits = defineEmits(['update:modelValue', 'fileChange'])

const cleanAvatar = ()=> {
	imgUrl.value = ''
	emits('update:modelValue', '')
}



// 头像上传处理
const handleAvatarSuccess = (res) => {
	if(res.code === 200) {
		imgUrl.value = res.data
		useMessage().success('头像上传成功')
		//上传成功绑定到父组件
		emits('update:modelValue', imgUrl.value)
	}
}

const beforeAvatarUpload = (file) => {
	const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
	const isLt5M = file.size / 1024 / 1024 < 5

	if (!isValidType) {
		useMessage().error('仅支持 JPG/PNG/GIF 格式!')
	}
	if (!isLt5M) {
		useMessage().error('图片大小不能超过5MB!')
	}
	emits('fileChange', file)
	return isValidType && isLt5M
}
</script>
<style scoped lang="scss">
.avatar-uploader {
	position: relative;
	:deep(.el-upload) {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);

		&:hover {
			border-color: var(--el-color-primary);
		}
	}

	.avatar {
		width: 120px;
		height: 120px;
		display: block;
		object-fit: cover;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}


	.avatar-delete{
		position: absolute;
		top: 5px;
		right: 5px;
		font-size: 18px;
		cursor: pointer;
		z-index: 99;
		visibility: hidden;
	}
	//显示删除按钮
	&:hover{
		.avatar-delete{
			visibility: visible;
		}
	}
}
</style>
